import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { App, Button, Form, Input } from 'antd';

import Dialog from '@/components/Dialog';
import useDevice, { DEVICES } from '@/hooks/useDevice';
import { setStore } from '@/reducers/common';
import { feedback } from '@/service/api';
import styles from './index.module.scss';

export default props => {
    const initState = () => ({ loading: false });
    const [state, setState] = useState(initState);
    const { feedbackVisible=false, userInfo={} } = useSelector(s => s.common);
    const dispatch = useDispatch();
    const deviceType = useDevice();
    const isPc = deviceType === DEVICES.DESKTOP;
    const [form] = Form.useForm();
    const { message } = App.useApp();

    const handleClose = () => {
        dispatch(setStore({ feedbackVisible: false }));
        form.resetFields();
        setState(initState);
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            const payload = {
                content: values.content,
            };

            setState(o => ({ ...o, loading: true }));
            const [res, err] = await feedback(payload);
            if(err) return message.warning(`${err.message || '提交失败'}`);
            message.success('感谢反馈，我们会尽快处理！');
            handleClose();
        } catch (e) {
            console.log(e)
        } finally {
            setState(o => ({ ...o, loading: false }));
        }
    };

    useEffect(() => {
        if (feedbackVisible) {
            // 打开时重置表单
            form.resetFields();
        }
    }, [feedbackVisible]);

    return (
        <Dialog
            className={styles['dialog']}
            open={feedbackVisible}
            onOpenChange={open => !open ? handleClose() : null}
            isPc={true}
            width={isPc ? 560 : '100%'}
            maskClosable={false}
        >
            <div className={styles['container']}>
                <div className={styles['header']}>意见反馈</div>
                <div className={styles['body']}>
                    <Form
                        form={form}
                        layout="vertical"
                        initialValues={{ content: '' }}
                    >
                        <Form.Item label="意见内容" name="content" rules={[{ required: true, message: '请填写意见内容' }]}> 
                            <Input.TextArea rows={6} maxLength={500} showCount placeholder="请描述你的意见" />
                        </Form.Item>
                    </Form>
                </div>
                <div className={styles['footer']}>
                    <Button onClick={handleClose}>取消</Button>
                    <Button type="primary" loading={state.loading} onClick={handleSubmit} style={{ marginLeft: 12 }}>提交</Button>
                </div>
            </div>
        </Dialog>
    )
}
